//
//  CheckoutHistoryViewController.m
//  CS Inventory Manager
//
//  Created by Billy Zoellers on 3/21/13.
//  Copyright (c) 2013 Transylvania University. All rights reserved.
//

#import "CheckoutHistoryNavigationViewController.h"
#import "CheckoutHistoryViewController.h"
#import "CheckoutRecordViewController.h"
#import "CheckoutRecord.h"
#import "CheckoutRecordPatron.h"

@interface CheckoutHistoryViewController () {
    
    /* xml */
	NSURL* url;
	NSMutableData* requestData;
	NSMutableString* theData;
	NSXMLParser* fileParser;
	CheckoutRecord *temp;
    CheckoutRecordPatron *tempPatron;
	BOOL noNetwork;
    
    NSMutableArray *ourCheckouts;
    
}

@end

@implementation CheckoutHistoryViewController
@synthesize delegate,ourPatron,ourItem;

-(BOOL)refreshXML:(id)sender{
    
    self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"Refreshing data..."];
    
    noNetwork = NO;
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    // drop the array & recreate it
    ourCheckouts = nil;
	ourCheckouts = [[NSMutableArray alloc] init];
    
    NSLog(@"Item: %@",[ourItem assetId]);
    NSLog(@"Patron: %@",[ourPatron lastName]);
    
    // get data from internet
    if (ourPatron && !ourItem) {
        // use url for patron
        NSString *urlstring = [NSString stringWithFormat:@"http://www.cs.transy.edu/zoellers/inventory/listCheckoutHistoryForPatron.php?secret=pass&id=%i",[ourPatron patronId]];
        
        url = [[NSURL alloc] initWithString:urlstring];
        
    } else if (!ourPatron && ourItem) {
        // use url for item
        NSString *urlstring = [NSString stringWithFormat:@"http://www.cs.transy.edu/zoellers/inventory/listCheckoutHistoryForItem.php?secret=pass&id=%i",[ourItem itemId]];
        
        url = [[NSURL alloc] initWithString:urlstring];
        
    } else {
        NSLog(@"error detecting type");
        
    }
    
	NSURLRequest *dataRequest = [NSURLRequest requestWithURL:url
												 cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
											 timeoutInterval:60];
	NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:dataRequest delegate:self];
	if (connection) {
		NSLog(@"refreshXML: Created connection request.");
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"MMM d, h:mm a"];
        NSString *lastUpdated = [NSString stringWithFormat:@"Last updated on %@",[formatter stringFromDate:[NSDate date]]];
        self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:lastUpdated];
        [self.refreshControl endRefreshing];
        
        return true;
	}
	else {
		NSLog(@"refreshXML: ERROR: Could not create connection request.");
		//Output no internet
        return false;
	}
	
}

- (IBAction)doneButton:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];    
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setDelegate:self.navigationController];
    
    [self setOurItem:[delegate passThroughItem]];
    [self setOurPatron:[delegate passThroughPatron]];
    
    [self refreshXML:nil];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [ourCheckouts count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"checkoutHistoryCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    CheckoutRecord *currentRecord = [ourCheckouts objectAtIndex:indexPath.row];
    
    // Configure the cell...
    if (ourPatron) {
        cell.textLabel.text = [currentRecord itemType];
    } else {
        if ([[currentRecord patrons] count] == 1) {
            cell.textLabel.text = [[[currentRecord patrons] objectAtIndex:0] name];
        } else {
            cell.textLabel.text = @"Multiple Patrons";
        }
    }
    
    // format the dates
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"MM/dd/yyyy"];
    NSString *inDateString = [dateFormat stringFromDate:[currentRecord inDate]];
    NSString *outDateString = [dateFormat stringFromDate:[currentRecord outDate]];
    
    // has it been turned in? if not, change inDateString to "current"
    if (!inDateString) {
        inDateString = @"current";
    }
    
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ - %@",outDateString,inDateString];
    
    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self performSegueWithIdentifier:@"CheckoutDetail" sender:[ourCheckouts objectAtIndex:indexPath.row]];
}


-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
        CheckoutRecordViewController *nextController = segue.destinationViewController;
        nextController.theRecord = sender;
        [nextController setDelegate:self];
}

/********************************************************************
 for xml parsing
 ********************************************************************/

//connection finished loading it's data
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	// DEBUGGING: NSLog(@"GRABBED DATA%@", requestData);
    if (requestData) {
        NSLog(@"connectionDidFinishLoading: Retrieved XML data. Beginning XML parsing process.");
    } else {
        NSLog(@"connectionDidFinishLoading: ERROR: No XML data retrieved.");
    }
	//allocate file parser
	fileParser = [[NSXMLParser alloc] initWithData:requestData];
	
	//set current object as delegate
	[fileParser setDelegate:self];
	//start parsing
	[fileParser parse];
    
    NSLog(@"connectionDidFinishLoading: Ending XML parsing process");
    fileParser = nil;
}


//Connection failed
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"\t\tconnection DidFailWithError: ERROR: Connection failed, trigger notification.");
	//Connection failed, tell the user
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Unable to connect." message:@"Your device is unable to connect to the network. Please check your network connection and try again." delegate:self cancelButtonTitle:@"Dismiss"  otherButtonTitles:nil, nil];
	[alert show];
	alert = nil;
	noNetwork = YES;
	[self.tableView reloadData];
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	
}
//Connection Started
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	//allocate a place to store the data until it is whole
	requestData = [[NSMutableData alloc] init];
	[requestData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	//Append data
	[requestData appendData:data];
}
//Found start tag
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
	if ([elementName isEqual:@"xml"]) {
		//Allocate a string that will hold the data
		theData = [[NSMutableString alloc] init];
	}
	else if ([elementName isEqual:@"checkout"]) {
		//allocate a temporary variable to hold the data until it is ready to be stored in the array
		temp = [[CheckoutRecord alloc] init];
        temp.patrons = [[NSMutableArray alloc] init];
	} else if ([elementName isEqual:@"copatron"]) {
        // allocate a new checkout patron
        tempPatron = [[CheckoutRecordPatron alloc] init];
    }
    
	if (![elementName isEqual:@"xml"]) {
		//black the string
		[theData setString:@""];
	}
}
//Found end tag while parsing
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
	//Check the end element name and store it in theData to the appropriate variable
	if ([elementName isEqual:@"xml"]) {
        
	} else if ([elementName isEqual:@"checkoutID"]) {
        [temp setCheckoutID:[theData intValue]];
        NSLog(@"Checkout ID# %d",[temp checkoutID]);
    } else if ([elementName isEqual:@"itemType"]) {
		[temp setItemType:[[NSString alloc] initWithString:theData]];
	} else if ([elementName isEqual:@"itemModel"]) {
		[temp setItemModel:[[NSString alloc] initWithString:theData]];
	} else if ([elementName isEqual:@"itemAssetID"]) {
        [temp setAssetNo:[[NSString alloc] initWithString:theData]];
    } else if ([elementName isEqual:@"patronName"]) {
        [tempPatron setName:[[NSString alloc] initWithString:theData]];
        NSLog(@"found copatron with patronName: %@",[tempPatron name]);
    } else if ([elementName isEqual:@"patronEmail"]) {
        [tempPatron setEmail:[[NSString alloc] initWithString:theData]];
    } else if ([elementName isEqual:@"patronId"]) {
            [tempPatron setId:[theData intValue]];
	} else if ([elementName isEqual:@"outDate"]) {
        NSString *dateString = [[NSString alloc] initWithString:theData];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        // this is imporant - we set our input date format to match our input string
        // if format doesn't match you'll get nil from your string, so be careful
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        // voila!
		[temp setOutDate:[dateFormatter dateFromString:dateString]];
    } else if ([elementName isEqual:@"dueDate"]) {
        NSString *dateString = [[NSString alloc] initWithString:theData];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        // this is imporant - we set our input date format to match our input string
        // if format doesn't match you'll get nil from your string, so be careful
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        // voila!
		[temp setDueDate:[dateFormatter dateFromString:dateString]];
    } else if ([elementName isEqual:@"returnDate"]) {
		NSString *dateString = [[NSString alloc] initWithString:theData];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        // this is imporant - we set our input date format to match our input string
        // if format doesn't match you'll get nil from your string, so be careful
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        // voila!
		[temp setInDate:[dateFormatter dateFromString:dateString]];
    } else if ([elementName isEqual:@"outNotes"]) {
		[temp setOutNotes:[[NSString alloc] initWithString:theData]];
    } else if ([elementName isEqual:@"inNotes"]) {
        [temp setInNotes:[[NSString alloc] initWithString:theData]];
    } else if ([elementName isEqual:@"profName"]) {
        [temp setProfName:[[NSString alloc] initWithString:theData]];
    } else if ([elementName isEqual:@"copatron"]) {
        // add the temp patron to the array of patrons
        [[temp patrons] addObject:tempPatron];
        NSLog(@"adding patron#%d to checkout with name %@",[[temp patrons] count],[tempPatron name]);
        tempPatron = nil;
    } else if ([elementName isEqual:@"checkout"]) {
        // add the CheckoutRecord to the array of checkouts
		[ourCheckouts addObject:temp];
		temp = nil;
    }
	
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
	[theData appendString:string];
}

- (void)parserDidEndDocument:(NSXMLParser *)parse
{
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    NSLog(@"\t\tparserDidEndDocument: Data retrieved, reloading table.");
	[self.tableView reloadData];
}


@end
